#!/bin/bash

#
# Initialization
export DRAW_INI=
export DRAW_CFG=
source $DRAW_INI
source $DRAW_CFG

# get command line parameters
while getopts dr:l:p:t: option
do
        case "$option" in
            d) DODEBUG=true;;               # option -d to print out commands
            r) RUN_DIR="$OPTARG";;
            l) LINE="$OPTARG";;
            p)                              # -p 1/2/3 to execute a particular phase, e.g.: -p1 -p2 -p3
              case "$OPTARG" in
                1) DOPHASE1=true;;
                2) DOPHASE2=true;;
                3) DOPHASE3=true;;
                4) DOPHASE4=true;;
                5) DOPHASE5=true;;
                6) DOPHASE6=true;;
              esac;;
            t) TEST_FUNCTION="$OPTARG";;    # execute function e.g.,   -t "stat _merged_nodup_uniq_recal"
        esac
done

#
# Globals
USER=$LOGNAME
export CMD_DIR=$CMD_DRAW
export REF_FASTA=$GENOME_REF
export SNPDB=$DBSNP_REF
export SNPDB_INDELS_ONLY=$DBSNP_REF
export BUNDLE_HAPMAP=$VAR_RECAL_BUNDLE_HAPMAP
export BUNDLE_OMNI=$VAR_RECAL_BUNDLE_OMNI
export BUNDLE_MILLS=$VAR_RECAL_BUNDLE_MILLS
export TARGET=$TARGETS_FILE
export FLANK=$TARGET_FLANKS_FILE
export SNPEFF=$SNPEFF_DB

export QSEQ_DIR=
export FASTQ_DIR=
export SAI_DIR=
export SAM_DIR=
export BAM_DIR=
export STAT_DIR=stat
export VCF_DIR=vcf
#
# User Configuration

###DATA_TYPE=(TILESQSEQ | TILESFASTQ | TILESELAND | ONEFASTQ | ONEFASTQSE) Single-End
###TARGET_COVERAGE=(AGILENT | NIMBLEGEN)

DATA_TYPE=
TARGET_COVERAGE=

#Template variables below
export RG_STR=
export RG_STR_PICARD=

export RGID=

export LINE=

export mbq=
export mmq=

if [ $DATA_TYPE == "TILESQSEQ" ]; then
 tiles=($(ls $QSEQ_DIR/*.txt*|sed -n 's/.*s_[0-9]\+_1_\([0-9]\+\).*/\1/p')) # this extracts 0001, 0002 .. XXXX from s_N_1_XXXX

elif [ $DATA_TYPE == "TILESFASTQ" ]; then
 tiles=($(ls $FASTQ_DIR/*.fastq*|sed -n 's/.*s_[0-9]\+_1_\([0-9]\+\).*/\1/p')) # this extracts 0001, 0002 .. XXXX from s_N_1_XXXX
 tilesR=($(ls $FASTQ_DIR/*.fastq*|grep -Po '[^/]+R1_[^\.]+')) # this extracts a different format
fi

#
# SUB
SUBCMD=$SUB
[[ $DODEBUG ]] && SUB="echo $SUB"

NUMJOBS=`qstat -u $USER|grep -c $USER`
export SUBARGS="-S /bin/bash -q $GRID_QUEUE -cwd -v DRAW_INI,DRAW_CFG,REF_FASTA,SNPDB -j y -o $STDOUT -hard -l h_stack=256m,h_vmem=1G"

#
# function libraries
source $CMD_DIR/lib/ngs.phase1_lib.pe.sh 
source $CMD_DIR/lib/ngs.phase2_lib.pe.sh 
source $CMD_DIR/lib/ngs.phase3_lib.pe.sh 


if [ ! -z "$TEST_FUNCTION" ] 
then
 eval $TEST_FUNCTION
 exit
fi

#############################################################
# PHASE 1 - Create BAM alignments                           #

if [[ $DOPHASE1 ]]; then
  echo "Phase 1"

  if [ $DATA_TYPE == "BAM" ]; then
		echo "Merging the following bam files"
		ls $BAM_DIR
		samtoolsMergeBam

  elif [[ $DATA_TYPE == "ONEFASTQ" || $DATA_TYPE == "ONEFASTQSE" ]]; then
  	bwaAlnOneFastq
  	bwaSampOneFastq
#	  mergeSamToBam
		addReadGroup $SAM_DIR/s_${LINE}_sequence.aligned.sam.gz $BAM_DIR/s_${LINE} Samp${RGID}
		mgBamSoftLink $BAM_DIR/s_${LINE}_rg.bam s_${LINE}_merged.bam 

  else
		if [ $DATA_TYPE == "TILESQSEQ" ]; then
			[ $(checkIncompleteFASTQ) == 1 ] && qseqToFastq
		fi

		[ $(checkIncompleteSAI) == 1 ]   && bwaAln
		[ $(checkIncompleteSAM) == 1 ]   && bwaSamp

		[ $(checkIncompleteBAM) == 1 ]   && addReadGroupTasks
		samtoolsMergeBam


	fi

fi


############################################################
#                                                          #
# PHASE 4 - Merge BAM : the pipeline might start here      #
#  																							           #
if [ $DOPHASE4 ]; then
  echo "Phase 4 - merging the following bam files"
  ls $BAM_DIR
  samtoolsMergeBam

fi
###################### EOF PHASE 4 #########################


############################################################
#                                                          #
# PHASE 2 - BAM Recalibration                              #
if [ $DATA_TYPE != "ONEFASTQ" ] && [[ $DOPHASE2 ]]; then
  echo "Phase 2"
 
 markdup
 doFlagStat "s_${LINE}_merged_markdup"
 countRead "s_${LINE}_merged_markdup" $TARGET
 countRead "s_${LINE}_merged_markdup"

 if [[ $REF_FASTA =~ 'hg' ]];then
    localRealignIndel
    recal "s_${LINE}_merged_markdup.indel_realign" "s_${LINE}" "realignIndelS2_$LINE"
 else
    recal "s_${LINE}_merged_markdup" "s_${LINE}" "markdup$LINE"
 fi

 picard_qc_metrics 
  
elif [ $DATA_TYPE == "ONEFASTQ" ] && [[ $DOPHASE2 ]]; then
  echo "Phase 2"

  sortSamOneFastq  
  dedupBamOneFastq

  recal 
  merge_chr_table

fi

###################### EOF PHASE 2 #########################


############################################################
#                                                          #
# PHASE 3 - Generate Stats                                 #
if [[ $DOPHASE3 ]]; then
 echo "Phase 3 - VariantCall and Generate Stats"
 target_coverages
 genome_coverage
 snpcal
 snpAnnotation
 collectSPeekMetrics
fi

###################### EOF PHASE 3 #########################


############################################################
#                                                          #
# PHASE 5 - populates SneakPeek                            #
if [[ $DOPHASE5 ]]; then
	echo "Phase 5 - populates SneakPeek"
	if [ -s ${LINE}_speek.txt ]; then
    insertSPeek
  else
		echo -e "${LINE}_speek.txt not found or empty."
  fi
fi

###################### EOF PHASE 5 #########################


############################################################
#                                                          #
# PHASE 6 - Additional Analyses                            #

if [ ! -z $TARGETS_FILE ] && [[ $DOPHASE6 ]]; then
    echo "Phase 6"
    target_coverages $TARGETS_FILE $TARGET_COVERAGE
fi

###################### EOF PHASE 6 #########################
